# Definition for a binary tree node.
from typing import Optional


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
        ret = 0
        def dfs(root: Optional[TreeNode], low: int, high: int):
            nonlocal ret
            if root is None:
                return
            if low <= root.val <= high:
                ret += root.val
                dfs(root.right, low, high)
                dfs(root.left, low, high)
            if root.val > high:
                dfs(root.left, low, high)
            if root.val < low:
                dfs(root.right, low, high)

        dfs(root, low, high)
        return ret
